package com.yuanluludev.lib_x5web

import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.webkit.JavascriptInterface
import android.widget.ProgressBar
import android.widget.RelativeLayout
import com.tencent.smtt.export.external.interfaces.*
import com.tencent.smtt.sdk.ValueCallback
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import com.yuanluludev.lib_base.base.BaseActivity
import com.yuanluludev.lib_utils.util.LogUtils
import com.yuanluludev.lib_utils.util.SizeUtils

/**
 * 基于X5 web 的页面基类
 */
abstract class BaseWebViewActivity : BaseActivity() {

    protected var mWebView: WebView? = null
    protected var pb: ProgressBar? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initWebView()
    }

    /**
     * 自定义初始化WebView设置，此处为默认 BaseWebViewActivity 初始化
     * 可通过继承该 Activity Override 该方法做自己的实现
     */
    protected open fun initWebView() {
        val mContainer = findViewById<ViewGroup>(getContainerID())
        mWebView = WebView(getContext())
        pb = ProgressBar(getContext(), null, android.R.attr.progressBarStyleHorizontal)

        val webViewLp = RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        ).apply {
            addRule(RelativeLayout.CENTER_IN_PARENT)
        }

        val pbLp =
            RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(3F))
                .apply {
                    addRule(RelativeLayout.ALIGN_PARENT_TOP)
                }

        mContainer?.addView(mWebView, webViewLp)
        mContainer?.addView(pb, pbLp)

        mWebView?.apply {
            this.settings.apply {
                javaScriptEnabled = true
                allowFileAccess = true
                setSupportZoom(true)
                builtInZoomControls = true
                databaseEnabled = true
                allowFileAccess = true
                domStorageEnabled = true

                initWebViewClient()
                initWebChromeClient()
                initJavaScriptInterface()
                val webUrl = getWebUrl()
                if (!TextUtils.isEmpty(webUrl)) {
                    mWebView?.loadUrl(webUrl)
                }
            }
        }
    }

    abstract fun getContainerID(): Int

    open fun getWebUrl(): String = ""

    open fun setTitleText(title: String) {}

    private fun initWebViewClient() {
        mWebView?.webViewClient = object : WebViewClient() {

            override fun onPageStarted(p0: WebView?, url: String?, fav: Bitmap?) {
                super.onPageStarted(p0, url, fav)
                LogUtils.e("onPageStarted, url = $url ")
            }

            override fun onPageFinished(p0: WebView?, p1: String?) {
                super.onPageFinished(p0, p1)
                LogUtils.e("onPageFinished,  p1 = $p1")
            }

            override fun onReceivedError(p0: WebView?, p1: Int, p2: String?, p3: String?) {
                LogUtils.e("onReceivedError: $p1, description: $p2, url: $p3")
            }

//            override fun shouldInterceptRequest(
//                webView: WebView,
//                webResourceRequest: WebResourceRequest?
//            ): WebResourceResponse {
//                return if (webResourceRequest?.url.toString().contains("debugdebug")) {
//                    var ins: InputStream? = null
//                    LogUtils.e("shouldInterceptRequest")
//                    try {
//                        ins = FileInputStream(File("/sdcard/1.png"))
//                    } catch (e: Exception) {
//                    }
//                    WebResourceResponse("image/*", "utf-8", ins)
//                } else {
//                    super.shouldInterceptRequest(webView, webResourceRequest)
//                }
//            }
        }
    }

    open fun onProgressChanged(newProgress: Int) {

    }

    private fun initWebChromeClient() {
        mWebView?.webChromeClient = object : WebChromeClient() {

            override fun onReceivedTitle(p0: WebView?, p1: String?) {
                super.onReceivedTitle(p0, p1)
                LogUtils.e("onReceivedTitle(), p1 = $p1")
                setTitleText(p1 ?: "")
            }

            override fun onProgressChanged(view: WebView, newProgress: Int) {
                LogUtils.e("onProgressChanged(), newProgress = $newProgress")
                onProgressChanged(newProgress)
                if (newProgress >= 100) {
                    pb?.apply {
                        progress = 100
                        this.visibility = View.GONE
                    }
                } else {
                    pb?.apply {
                        if (this.visibility == View.GONE) {
                            this.visibility = View.VISIBLE
                        }
                        this.progress = newProgress
                    }
                }
            }

            override fun onJsAlert(
                webView: WebView,
                url: String,
                message: String,
                result: JsResult
            ): Boolean {
                //可以弹框或进行其它处理，但一定要回调result.confirm()或者cancel()
                //这里要返回true否则内核会进行提示

                result.confirm()
                return true
            }

            override fun onJsConfirm(
                webView: WebView,
                url: String,
                message: String,
                result: JsResult
            ): Boolean {
                //可以弹框或进行其它处理，但一定要回调result.confirm()或者cancel()
                result.confirm()
                return true
            }

            override fun onJsBeforeUnload(
                webView: WebView,
                url: String,
                message: String,
                result: JsResult
            ): Boolean {
                //页面即将跳转
                // 可以弹框或进行其它处理，但一定要回调result.confirm或者cancel
                result.confirm()
                return true
            }

            override fun onJsPrompt(
                webView: WebView,
                url: String,
                message: String,
                defaultValue: String,
                result: JsPromptResult
            ): Boolean {
                result.confirm()
                return true
            }

            override fun onShowFileChooser(
                webView: WebView,
                filePathCallback: ValueCallback<Array<Uri>>,
                fileChooserParams: FileChooserParams
            ): Boolean {
                LogUtils.e("openFileChooser: " + fileChooserParams.mode)
                return true
            }

            override fun onGeolocationPermissionsShowPrompt(
                origin: String,
                geolocationPermissionsCallback: GeolocationPermissionsCallback
            ) {

            }

        }
    }

    private fun initJavaScriptInterface() {
        mWebView?.addJavascriptInterface(object : WebViewJavaScriptFunction {
            override fun onJsFunctionCalled(tag: String?) {}

            @JavascriptInterface
            fun openQRCodeScan() {

            }

            @JavascriptInterface
            fun openDebugX5() {
                mWebView?.loadUrl("http://debugx5.qq.com")
            }

            @JavascriptInterface
            fun openWebkit() {

            }
        }, "Js2Android")
    }

    override fun onDestroy() {
        mWebView?.destroy()
        super.onDestroy()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView != null && mWebView?.canGoBack() == true) {
                mWebView?.goBack()
                return true
            }
            finish()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

}